import 'dart:async';
import 'dart:collection';

import 'package:flutter/services.dart';
import 'package:flutter_module/core/app_env.dart';
import 'package:flutter_module/core/bridge_interface.dart';
import 'package:flutter_module/model/native_image_options.dart';
import 'package:flutter_module/model/native_media_type.dart';

/// Create by kyluzoi
/// Date: 2021-08-09
///
/// Description: 用于跟我们原生进行桥接

class FlutterPlatformBridge implements BridgeInterface {
  static FlutterPlatformBridge _instance = FlutterPlatformBridge._();

  MethodChannel _bridge = const MethodChannel('FlutterPlatformBridge');

  var _listeners = {}; // 页面来向我们 native 端注册监听，接收消息
  var header;

  FlutterPlatformBridge._() {
    _bridge.setMethodCallHandler((MethodCall call) {
      String method = call.method;
      if (_listeners[method] != null) {
        return _listeners[method](call);
      }
      // fix null not return type
      return Future.value(null);
    });
  }

  static FlutterPlatformBridge getInstance() {
    return _instance;
  }

  register(String method, Function(MethodCall) callBack) {
    _listeners[method] = callBack;
  }

  unRegister(String method) {
    _listeners.remove(method);
  }

  @override
  goToNative(String? uri, {Map? params}) {
    // fix 可传 uri , params ，可用于传递特殊参数给 native 接收
    params = params ?? Map();
    params["path"] = uri ?? params["path"];
    _bridge.invokeMethod("goToNative", params);
  }

  @override
  onBack(Map? prams) {
    _bridge.invokeMethod("onBack", prams);
  }

  @override
  Future<Map<String, String>> getHeaderParams() async {
    Map header = await _bridge.invokeMethod('getHeaderParams', {});
    return this.header = Map<String, String>.from(header);
  }

  MethodChannel bridge() {
    return _bridge;
  }

  @override
  Future<EnvConfig> getHost() async {
    Map env = await _bridge.invokeMethod('getHost', {});
    AppEnv.app2Env = new EnvConfig(
        env: EnvType.custom,
        apiBaseURL: env["apiBaseURL"],
        webBaseURL: env["webBaseURL"],
        h5BaseURL: env["h5BaseURL"],
        imgBaseURL: env["imgBaseURL"]);
    return AppEnv.app2Env!;
  }

  @override
  Future<String> selectAndUploadFromPhotos(
      {NativeMediaType displayMediaType = NativeMediaType.image,
      NativeImageOptions? imageOptions}) async {
    try {
      Map<String, dynamic> params = {};
      params['displayMediaType'] =
          displayMediaType == NativeMediaType.image ? 'image' : 'video';
      params['imageOptions'] = imageOptions?.toMap();
      final url = await _bridge.invokeMethod<String>(
          'selectAndUploadFromPhotos', params);
      print('上传成功 $url');
      return url ?? '';
    } catch (e, s) {
      print(s);
      return '';
    }
  }
}
